package net.sevear.chaos.douban.shuo
{
	import com.adobe.serialization.json.JSON;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	
	import net.sevear.chaos.douban.DBShuoManager;
	import net.sevear.chaos.utils.DataUtil;
	import net.sevear.chaos.utils.Logger;
	import net.sevear.chaos.vo.TrackInfo;
	import net.sevear.chaos.vo.UserInfo;
	
	public class DBShuoSender extends EventDispatcher
	{
		public static const SHUO_RECOMMEND_URI				:String = "/!service/share";

		public static const OP_RECOMMEND_1				:int = 0;
		public static const OP_RECOMMEND_2				:int = 1;
		
		private var loader:URLLoader;
		private var step:int = OP_RECOMMEND_1;
		private var isSendingRequest:Boolean = false;
		private var trackInfo:TrackInfo;
		private var destUsers:Array;
		public function DBShuoSender()
		{
			super(null);
			loader = new URLLoader();
			loader.addEventListener(Event.COMPLETE,onLoaderComplete);
			loader.addEventListener(IOErrorEvent.IO_ERROR,onIOErrorEvent);
		}
		
		public function recommend(trackInfo:TrackInfo,destUsers:Array=null):Boolean{
			if(isSendingRequest==false){
				this.trackInfo = new TrackInfo();
				DataUtil.generateNewTrack(this.trackInfo,trackInfo);
				this.destUsers = destUsers;
				step = OP_RECOMMEND_1;
				isSendingRequest = true;
				loader.load(buildReq1());
				return true;
			}else{
				return false;
			}
		}
		
		private function onLoaderComplete(e:Event):void{
			switch (step){
				case OP_RECOMMEND_1:
					recommend2((e.currentTarget as URLLoader).data as String);
					break;
				case OP_RECOMMEND_2:
					isSendingRequest = false;
					dispatchEvent(new DBShuoEvent(DBShuoEvent.SEND_SHARE_SUCCESSFULLY,this.trackInfo));
					Logger.getInstance().logInfo("sid: ",this.trackInfo.sid," name:",this.trackInfo.name," 推荐到豆瓣成功");
					break;
			}
		}
		
		private function recommend2(html:String):void{
			//parse the shore url
			var attachmentsMatchs:Array = html.match(/<input class="attachments" [^>]+>/);
			if(attachmentsMatchs!=null){
				var valueIdx:int = (attachmentsMatchs[0] as String).search(/value=\"/);
				var jsonStr:String = (attachmentsMatchs[0] as String).slice(valueIdx+7,
					(attachmentsMatchs[0] as String).length-3);
				jsonStr = jsonStr.replace(/&quot;/g,'"');
				jsonStr = jsonStr.replace(/\\\//g,'/');
				jsonStr = jsonStr.replace(/&amp;/g,'&');
				var jsonObj:Object = JSON.decode(jsonStr);
				jsonObj[0].href = "http://douban.fm/?start="+trackInfo.sid+"g"+trackInfo.ssid+"g0&cid=0";
				var vars:URLVariables = new URLVariables();
				var text:String = "";
				if(destUsers!=null){
					//@豆瓣用户搜
					for each(var user:UserInfo in this.destUsers){
						text+="@"+user.dbUID+" ";
					}
				}
				//<input type="hidden" name="ck" value="9t51"/>
				var ckMatchs:Array = html.match(/<input type="hidden" name="ck" value="[-\da-zA-Z:+=]*"\/>/);
				if(ckMatchs!=null){
					var ck:String = (ckMatchs[0] as String).slice(
						'<input type="hidden" name="ck" value="'.length,
						(ckMatchs[0] as String).length-3);
					vars.ck = ck;
				}
				text += "recommended by #DouChaos#"
				vars.text = text;
				vars.attachments = JSON.encode(jsonObj);
				vars.apikey = "079055d6a0d5ddf816b10183e28199e8";
				
				vars.redir = "";
				vars.comment = "";
				vars.otext 	= "";
				vars.action =  "";
				vars.sub_action = "";
				
				try{
					loader.close();
				}catch(e:Error){
				}
				
				var rst:URLRequest = new URLRequest(DBShuoManager.SHUO_SERVER+SHUO_RECOMMEND_URI);
				rst.data = vars;
				rst.method = URLRequestMethod.POST;
				rst.requestHeaders.push(new URLRequestHeader("Referer","http://douban.fm/"));
				step = OP_RECOMMEND_2;
				loader.load(rst);
			}else{
				Logger.getInstance().logError("Share to DouBan Shuo Failed");
				isSendingRequest = false;
				dispatchEvent(new DBShuoEvent(DBShuoEvent.SEND_SHARE_FAILED,this.trackInfo));
			}
			
		}
		
		private function buildReq1():URLRequest{
			var text:String = "";
			var vars:URLVariables = new URLVariables();
			
			vars.name = trackInfo.name;
			vars.herf = "http://douban.fm/?start="+trackInfo.sid+"g"+trackInfo.ssid+"g0&cid=0";
			vars.desc = "(来自豆瓣FM-私人兆赫)";
			vars.image = trackInfo.albumImgURL;
			vars.text = text;
			vars.apikey = "079055d6a0d5ddf816b10183e28199e8";
			
			var rst:URLRequest = new URLRequest(DBShuoManager.SHUO_SERVER+SHUO_RECOMMEND_URI);
			rst.data = vars;
			rst.method = URLRequestMethod.GET;
			rst.manageCookies = true;
			return rst;
		}
		
		private function onIOErrorEvent(e:IOErrorEvent):void{
			isSendingRequest = false;
			Logger.getInstance().logError(e.text);
		}
	}
}